<template>
    <div class="table-container">
        <div class="fixed-rows">
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Age</th>
                        <th>Address</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in fixedRows" :key="index">
                        <td>{{ item.name }}</td>
                        <td>{{ item.age }}</td>
                        <td>{{ item.address }}</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <table>
            <tbody>
                <tr v-for="(item, index) in scrollingRows" :key="index">
                    <td>{{ item.name }}</td>
                    <td>{{ item.age }}</td>
                    <td>{{ item.address }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    import { ref } from 'vue';

    export default {
        setup() {
            const fixedRows = ref([
                { name: 'Alice', age: 28, address: 'New York No. 1 Lake Park' },
                { name: 'Bob', age: 30, address: 'London No. 1 Lake Park' },
                { name: 'Cathy', age: 25, address: 'Sidney No. 1 Lake Park' },
                { name: 'David', age: 22, address: 'Shanghai No. 1 Lake Park' },
            ]);

            const scrollingRows = ref([
                { name: 'Eva', age: 24, address: 'Beijing No. 1 Lake Park' },
                { name: 'Frank', age: 29, address: 'Tokyo No. 1 Lake Park' },
                { name: 'George', age: 27, address: 'Berlin No. 1 Lake Park' },
                { name: 'Helen', age: 26, address: 'Paris No. 1 Lake Park' },
                { name: 'Ivan', age: 31, address: 'Moscow No. 1 Lake Park' },
            ]);

            const container = ref(null);
            const fixedRowsRef = ref(null);

            const handleScroll = () => {
                if (container.value && fixedRowsRef.value) {
                    fixedRowsRef.value.style.transform = `translateY(${container.value.scrollTop}px)`;
                }
            };

            return {
                fixedRows,
                scrollingRows,
                container,
                fixedRowsRef,
                handleScroll,
            };
        },
    };
</script>

<style scoped>
    .table-container {
        position: relative;
        overflow: auto;
        height: 300px;
        /* 设置容器的高度 */
    }

    .fixed-rows {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1;
        background-color: white;
    }

    table {
        width: 100%;
        border-collapse: collapse;
    }

    th,
    td {
        padding: 8px;
        text-align: left;
        border-bottom: 1px solid #ddd;
    }
</style>